package com.mew.chess.core.game.lh.game.message;

import cn.hutool.core.util.RandomUtil;
import com.mew.chess.core.game.lh.game.common.LhBetType;
import com.mew.chess.core.game.lh.game.common.LhConstantValue;
import com.zebra.common.ZebraBaseMessage;
import io.netty.buffer.ByteBuf;
import lombok.*;

import java.util.ArrayList;
import java.util.List;


@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class LhHistoryMessage extends ZebraBaseMessage<LhHistoryMessage> {

    private List<Integer> history = new ArrayList<>(LhConstantValue.HISTORY_NUMBER);; //negative lose; positive win
    private List<List<Integer>> road = new ArrayList<>(LhConstantValue.ROAD_NUMBER);; //negative lose; positive win

    public void addHistory(int type){

        if (null==history){
            history = new ArrayList<>(LhConstantValue.HISTORY_NUMBER);
        }
        history.add(type);
        if (history.size()> LhConstantValue.HISTORY_NUMBER){
            history.remove(0);
        }

        addRoad();
    }

    public void addRoad(){
        int type = history.get(history.size()-1);
        if (road.size()>0 && (road.get(road.size() - 1).get(0)==type||type == LhBetType.HE.code())){

            road.get(road.size() - 1).add(type);

        }else {
            ArrayList<Integer> list = new ArrayList<>();
            list.add(type);
            road.add(list);
        }

        int sum = road.stream().filter(l -> l.stream().filter(i->i!=0).count() > 6).mapToInt(l -> (int) (l.stream().filter(i->i!=0).count() - 6)).sum();
        int n = 0;
        while (( n = (road.size()+sum-LhConstantValue.ROAD_NUMBER))>0){
            road.remove(0);
            sum = road.stream().filter(l -> l.size() > 6).mapToInt(l -> l.size() - 6).sum();
        }

    }


    @Override
    public void write(ByteBuf b) {


        writeMsg(b);
    }

    public void writeMsg(ByteBuf b) {

        writeIntArray(b,history.stream().mapToInt(Integer::intValue).toArray());

        writeInt(b,road.size());
        for (List<Integer> list : road) {
            writeIntArray(b,list.stream().mapToInt(Integer::intValue).toArray());
        }

    }

    @Override
    public LhHistoryMessage read(ByteBuf b) {
        return null;
    }

    public static void main(String[] args) {
        LhHistoryMessage message = new LhHistoryMessage();
        for (int i = 0; i < 20; i++) {
            int anInt = RandomUtil.randomInt(3);
            message.addHistory(anInt);
            System.out.println(message);
        }
    }
}
